<template>
  <el-container class="layout-container">
    <el-aside width="200px">
      <div class="aside-first">
        <el-image :src="logoUrl" :fit="'scale-down'" />
      </div>

      <el-menu
        active-text-color="#ffd04b"
        background-color="#232323"
        text-color="#fff"
        :default-active="$route.path"
        router>
        <el-sub-menu index="admin-users">
          <template #title>
            <el-icon>
              <User />
            </el-icon>
            <span>用户管理</span>
          </template>
          <el-menu-item index="/admin/users">
            <el-icon>
              <User />
            </el-icon>
            <span>用户列表</span>
          </el-menu-item>
        </el-sub-menu>

        <el-sub-menu index="admin-time">
          <template #title>
            <el-icon>
              <Clock />
            </el-icon>
            <span>时间管理</span>
          </template>
          <el-menu-item index="/admin/time">
            <el-icon>
              <Clock />
            </el-icon>
            <span>学习记录</span>
          </el-menu-item>
        </el-sub-menu>
      </el-menu>
    </el-aside>

    <el-container>
      <el-header>
        <div><strong>{{ userInfoStore.info.username }}</strong></div>
        <dark-mode-slider></dark-mode-slider>
        <el-dropdown placement="bottom-end" @command="handleCommand">
          <span class="el-dropdown__box">
            <el-avatar
              :src="userInfoStore.info.avatarUrl ? userInfoStore.info.avatarUrl : 'https://img2.baidu.com/it/u=3926734404,2114692953&fm=253&fmt=auto&app=138&f=JPEG?w=807&h=800'"/>
            <el-icon><CaretBottom /></el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="logout" :icon="SwitchButton">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </el-header>

      <el-main class="el-main">
        <h2 class="page-title">学习记录列表</h2>
        <el-table
          :data="learningRecords"
          stripe
          border
          :loading="loading"
          empty-text="暂无学习记录">
          <el-table-column prop="learnId" label="记录ID" width="100" />
          <el-table-column prop="userId" label="用户ID" width="100" />
        <!-- <el-table-column label="用户名" width="120">
            <template #default="scope">
              {{ getUserName(scope.row.userId) }}
            </template>
          </el-table-column>--> 
          <el-table-column label="开始时间" width="180">
            <template #default="scope">
              {{ formatDateTime(scope.row.startTime) }}
            </template>
          </el-table-column>
          <el-table-column label="结束时间" width="180">
            <template #default="scope">
              {{ formatDateTime(calculateEndTime(scope.row.startTime, scope.row.duration)) }}
            </template>
          </el-table-column>
          <el-table-column label="学习时长" width="120">
            <template #default="scope">
              {{ formatDuration(scope.row.duration) }}
            </template>
          </el-table-column>
          <el-table-column label="学习内容" min-width="150">
            <template #default="scope">
              {{ getSubjectName(scope.row.subject) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button type="text" size="small" @click="handleView(scope.row)">查看详情</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-main>

      <el-footer>基于Deepseek的408考研小助手</el-footer>
    </el-container>
    <small-window></small-window>
  </el-container>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { CaretBottom, User, Clock, SwitchButton } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router'; // 关键修复：添加useRouter导入
import DarkModeSlider from '@/components/DarkModeSlider.vue';
import SmallWindow from '@/components/SmallWindow.vue';
import { selectAll } from '@/api/learn.js';
import { userInfoService } from '@/api/user.js';
import useUserInfoStore from '@/stores/userInfo.js';
import { useTokenStore } from '@/stores/token.js';
import { useThemeStore } from '@/stores/theme.js';

const router = useRouter(); // 使用导入的useRouter
const tokenStore = useTokenStore();
const userInfoStore = useUserInfoStore();
const themeStore = useThemeStore();
const logoUrl = computed(() => themeStore.logoUrl);
const learningRecords = ref([]);
const userMap = ref({});
const loading = ref(false);

// 获取所有学习记录
const fetchLearningRecords = async () => {
  loading.value = true;
  try {
    const result = await selectAll();
    console.log('学习记录数据:', result);
    learningRecords.value = result.data || [];
  } catch (error) {
    console.error('获取学习记录失败:', error);
    ElMessage.error('获取学习记录失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 获取用户信息映射
const fetchUserMap = async () => {
  try {
    const result = await userInfoService.selectAll();
    userMap.value = result.data.reduce((map, user) => {
      map[user.userId] = user.username;
      return map;
    }, {});
  } catch (error) {
    console.error('获取用户信息失败:', error);
    userMap.value = {};
  }
};

// 根据用户ID获取用户名
const getUserName = (userId) => {
  return userMap.value[userId] || '未知用户';
};

// 计算结束时间
const calculateEndTime = (startTime, durationMinutes) => {
  if (!startTime) return null;
  const start = new Date(startTime);
  return new Date(start.getTime() + durationMinutes * 60 * 1000);
};

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '';
  const date = new Date(dateTime);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
};

// 格式化时长
const formatDuration = (minutes) => {
  if (!minutes || isNaN(minutes)) return '0分钟';
  if (minutes < 60) {
    return `${minutes}分钟`;
  } else {
    const hours = Math.floor(minutes / 60);
    const mins = minutes % 60;
    return `${hours}小时${mins}分钟`;
  }
};

// 获取学科名称
const getSubjectName = (subjectId) => {
  const subjectMap = {
    1: '数据结构',
    2: '计算机组成原理',
    3: '操作系统',
    4: '计算机网络',
    5: '综合练习'
  };
  return subjectMap[subjectId] || `未知学科(${subjectId})`;
};

// 查看详情
const handleView = (record) => {
  ElMessageBox.alert(`
    <div class="detail-item"><span class="detail-label">记录ID:</span> ${record.learnId}</div>
    <div class="detail-item"><span class="detail-label">用户ID:</span> ${record.userId}</div>
    <div class="detail-item"><span class="detail-label">用户名:</span> ${getUserName(record.userId)}</div>
    <div class="detail-item"><span class="detail-label">开始时间:</span> ${formatDateTime(record.startTime)}</div>
    <div class="detail-item"><span class="detail-label">结束时间:</span> ${formatDateTime(calculateEndTime(record.startTime, record.duration))}</div>
    <div class="detail-item"><span class="detail-label">学习时长:</span> ${formatDuration(record.duration)}</div>
    <div class="detail-item"><span class="detail-label">学习内容:</span> ${getSubjectName(record.subject)}</div>
  `, '学习记录详情', {
    dangerouslyUseHTMLString: true,
    customClass: 'detail-dialog',
    confirmButtonText: '关闭'
  });
};

onMounted(async () => {
  await fetchUserMap();
  await fetchLearningRecords();
});

const handleCommand = (command) => {
  if (command === 'logout') {
    ElMessageBox.confirm('您确认要退出吗?', '温馨提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(() => {
        tokenStore.removeToken();
        userInfoStore.removeInfo();
        localStorage.removeItem('role');
        router.push('/login'); // 正确使用router
        ElMessage.success('退出登录成功');
      })
      .catch(() => {
        ElMessage.info('用户取消了退出登录');
      });
  } else {
    router.push(command); // 正确使用router
  }
};
</script>

<style lang="scss" scoped>
.layout-container {
  height: 100vh;

  .el-aside {
    background-color: #232323;

    .aside-first {
      @include hold(100, 10);
      @include position-center-box("row,column");
    }

    .el-menu {
      border-right: none;
    }
  }

  .el-header {
    background-color: $global-background-color;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .el-dropdown__box {
      display: flex;
      align-items: center;

      .el-icon {
        color: #999;
        margin-left: 10px;
      }

      &:active,
      &:focus {
        outline: none;
      }
    }
  }

  .el-main {
    background-color: $global-background-color;
    padding: 20px;
    
    .page-title {
      margin-bottom: 20px;
      font-size: 18px;
      color: #333;
    }
  }

  .el-footer {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    color: #666;
  }

  .detail-dialog {
    .detail-item {
      margin-bottom: 10px;
    }
    .detail-label {
      display: inline-block;
      width: 80px;
      color: #606266;
    }
  }
}
</style>